package com.yoyo.yyadsdk.serv;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.anye.greendao.gen.AdvScreenEntityDao;
import com.anye.greendao.gen.AppEntityDao;
import com.anye.greendao.gen.ConfigEntityDao;
import com.anye.greendao.gen.DaoSession;
import com.anye.greendao.gen.MonitorTimeEntityDao;
import com.anye.greendao.gen.PullEntityDao;
import com.anye.greendao.gen.PushEntityDao;
import com.anye.greendao.gen.RuleListEntityDao;
import com.anye.greendao.gen.ShortcutEntityDao;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yoyo.yyadsdk.api.IConfigApi;
import com.yoyo.yyadsdk.bean.BaseBean;
import com.yoyo.yyadsdk.bean.PullBean;
import com.yoyo.yyadsdk.bean.dao.AdvScreenEntity;
import com.yoyo.yyadsdk.bean.dao.ConfigEntity;
import com.yoyo.yyadsdk.bean.dao.PullEntity;
import com.yoyo.yyadsdk.bean.dao.RuleListEntity;
import com.yoyo.yyadsdk.bean.dao.ShortcutEntity;
import com.yoyo.yyadsdk.config.Constants;
import com.yoyo.yyadsdk.config.PullFeature;
import com.yoyo.yyadsdk.util.Aes;
import com.yoyo.yyadsdk.util.AlarmUtils;
import com.yoyo.yyadsdk.util.ApiManage;
import com.yoyo.yyadsdk.util.ErrorAction;
import com.yoyo.yyadsdk.util.GreenDaoManager;
import com.yoyo.yyadsdk.util.NetWorkUtil;
import com.yoyo.yyadsdk.util.PullUtils;
import com.yoyo.yyadsdk.util.SpUtil;
import com.yoyo.yyadsdk.util.StringUtils;
import com.yoyo.yyadsdk.util.TimeUtils;


import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.yoyo.yyadsdk.config.Constants.ENABLED_STATUS;

public class UpdateDataService extends Service {

    private static final String TAG = "UpdateDataService";
    private Disposable mDisposable;
    private DaoSession mDaoSession;

    public static void getInstance(Context context) {
        if (SpUtil.getHasReportBaseData()) {
            context.startService(new Intent(context, UpdateDataService.class));
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mDaoSession = GreenDaoManager.getInstance().getDaoSession();
        checkLocalData();
    }

    /**
     * 检测本地数据更新
     */
    private void checkLocalData() {
        if (!SpUtil.getHasReportBaseData()) {
            return;
        }
        SpUtil.setHasReportBaseData();
        ConfigEntity configEntity = Constants.getConfigEntity();
        final long getInterval = (configEntity == null || configEntity.getGetInterval() < 1) ? TimeUtils.DAY : (configEntity.getGetInterval() * TimeUtils.SECOND);
        if (!NetWorkUtil.isNetworkConnected(this)) {
            AlarmUtils.addTask(PullFeature.ALARM_UPDATE_DATA, "", getInterval, false, 0);
            stopSelf();
            return;
        }
        String city = SpUtil.getCity(getApplicationContext());
        StringBuilder builder = new StringBuilder();
        builder.append("lastTime=").append(configEntity == null ? 0 : configEntity.getLastUpdateTime())
                .append("&searchIp=").append(StringUtils.notNull(city, "1"))
                .append("&timestamp=").append(System.currentTimeMillis());
//        Log.i("openPushAuthority==", builder.toString());
        String key = Aes.encode(builder.toString(), Aes.keyBytes);
        mDisposable = ApiManage.getInstance().getApi(IConfigApi.class, false)
                .getConfig(key)
                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String pull) {
//                        Log.e(TAG, pull);
                        Gson gson = new Gson();
                        BaseBean<PullBean> responseBody = gson.fromJson(pull, new TypeToken<BaseBean<PullBean>>() {
                        }.getType());
                        if (!responseBody.getResp_status().equals(Constants.SUCCESS)) {
                            stopSelf();
                            return;
                        }
                        PullBean pullBean = responseBody.getResp_data();
                        String addr = pullBean.getAddr();
                        if (!StringUtils.isNull(addr))
                            SpUtil.setCity(getApplicationContext(), addr);

                        PullEntityDao pullEntityDao = mDaoSession.getPullEntityDao();
                        AppEntityDao appEntityDao = mDaoSession.getAppEntityDao();
                        ConfigEntityDao configEntityDao = mDaoSession.getConfigEntityDao();
                        RuleListEntityDao ruleListBeanDao = mDaoSession.getRuleListEntityDao();
                        MonitorTimeEntityDao monitorTimeDao = mDaoSession.getMonitorTimeEntityDao();

                        PushEntityDao pushEntityDao = mDaoSession.getPushEntityDao();
                        AdvScreenEntityDao advScreenEntityDao = mDaoSession.getAdvScreenEntityDao();
                        ShortcutEntityDao shortcutEntityDao = mDaoSession.getShortcutEntityDao();

                        ruleListBeanDao.deleteAll();
                        monitorTimeDao.deleteAll();
                        pullEntityDao.deleteAll();
                        appEntityDao.deleteAll();
                        configEntityDao.deleteAll();

                        pushEntityDao.deleteAll();
                        advScreenEntityDao.deleteAll();
                        shortcutEntityDao.deleteAll();

                        for (RuleListEntity r : pullBean.getRuleList()) {
                            r.setInBlackRule(PullUtils.inBlackRuleList(getApplicationContext(), r));
                            r.setInWhiteRule(PullUtils.inWhiteRuleList(getApplicationContext(), r));
                        }

                        ruleListBeanDao.insertOrReplaceInTx(pullBean.getRuleList());
                        pullEntityDao.insertOrReplaceInTx(pullBean.getPullList());
                        appEntityDao.insertOrReplaceInTx(pullBean.getAppList());

                        ConfigEntity config = pullBean.getConfig();
                        configEntityDao.insertOrReplaceInTx(config);
                        monitorTimeDao.insertOrReplaceInTx(pullBean.getMonitorList());

                        pushEntityDao.insertOrReplaceInTx(pullBean.getPushList());
                        advScreenEntityDao.insertOrReplaceInTx(pullBean.getAdvScreenList());
                        shortcutEntityDao.insertOrReplaceInTx(pullBean.getShortcutList());

                        PullFeature.setPullFeatureInterval(config.getInterval());
                        PullFeature.setAdFeatureInterval(config.getAdInterval());
                        Constants.setConfigEntity(config);
                        //设置周期时间
                        SpUtil.setAdPeriod(config.getAdPeriod() * TimeUtils.SECOND);

                        long interval = TimeUtils.DAY;
                        if (config.getGetInterval() > 0) {
                            interval = config.getGetInterval() * TimeUtils.SECOND;
                        }
                        AlarmUtils.addTask(PullFeature.ALARM_UPDATE_DATA, "", interval, false, 0);

                        Integer enabledStatus = responseBody.getResp_data().getConfigList().getEnable();
                        ENABLED_STATUS = !(enabledStatus != null && enabledStatus != 1);
                        SpUtil.setConfigEnable(!(enabledStatus != null && enabledStatus != 1));
                        if (!ENABLED_STATUS) {
                            stopSelf();
                            return;
                        }

                        if (Build.VERSION.SDK_INT < 26) {
                            //添加快捷方式
                            long currentTimeMillis = System.currentTimeMillis();
                            long time = TimeUtils.DAY;
                            for (ShortcutEntity s : pullBean.getShortcutList()) {
                                long diff = s.getStartTime() - currentTimeMillis;
                                time = Math.min(diff, time);
                                if (time <= 0) {
                                    time = 0;
                                    break;
                                }
                            }
                            AlarmUtils.addTask(PullFeature.ALARM_SHORT_CUT, "", time, false, 0);
                        }
                        stopSelf();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        AlarmUtils.addTask(PullFeature.ALARM_UPDATE_DATA, "", getInterval, false, 0);
                        ErrorAction.print(throwable);
                        stopSelf();
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopDisposable();
    }

    private void stopDisposable() {
        if (mDisposable != null && !mDisposable.isDisposed())
            mDisposable.dispose();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
